<template>
  <el-dialog
    title="高级搜索"
    :visible.sync="dialogFormVisible"
    :modal="false"
    :fullscreen="false"
    custom-class="dialog-advsearch"
    top="35px"
    @open="handleOpen"
    @opened="handleOpened"
    ref="dialog"
    >
    <el-card
      class="dialog-search-box-card"
      shadow="never"
      :body-style="cardBodyHeight"
      >
      <el-form :model="params" size="mini">
        <el-form-item
          v-for="(item, index) in searchItems"
          :key="index"
          :label="item.title"
          :prop="item.name"
          label-width="120px"
          >
          <component
            :is="item.content"
            :fld="item"
            :ref="item.name"
            :value="isset(params[item.name],'value')?params[item.name].value:params[item.name]"
            :display-text="isset(item,'displayText')?item.displayText:''"
            @input="params[item.name]=arguments[0]"
            :row="params"
          ></component>
        </el-form-item>
      </el-form>
    </el-card>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleOk">确 定</el-button>
      <el-button @click="dialogFormVisible=false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
define(['vue','Common'],function(vue,Common){
  return vue.component('comp-advsearch-dialog',{
    template: template,
    props:['items'],
    data: function() {
      return {
        dialogFormVisible : false,
        //各个表单空间得数据model
        params: {},
        //预置的数据源，在弹框各个组件没有初始化之前就需要进行提前预置用，
        //比如从localstorage中获得的搜索默认项，在弹框打开前就需要保存起来，打开后覆盖
        paramsInit:{},
        formLabelWidth: '120px',
        //需要构造的搜索控件
        // searchConfig:[],
        //配置文件中定义了所有的searchItem,
        searchItems:[],
        // items:[],
        cardBodyHeight: {'max-height':'420px','overflow':'auto','padding':'0px 15px'},
        //高级搜索条件的描述
        descAdvParams:'',
      };
    },
    methods:{
      handleOpened(){
        // dump('Opened',this.paramsInit,this.params);
        Object.assign(this.params,this.paramsInit);
        //发生在组件初始化后，这里的$refs已经生效
        // this.$refs.productId[0].text='asdfasdfasdf';
      },
      handleOpen() {
        // dump('open',this.params.compName);
        this.$emit('open');
      },
      //isset函数继承
      isset: Common.isset,
      //将所有的搜索项默认值置为空,清空标签时触发
      clearAll : function() {
        for(var k in this.params) {
          this.clearItem(k);
        }
      },
      //将某个表单项置为空,修改标签时触发
      clearItem : function(key) {
        var item = this.params[key];
        if(typeof(item)=='string') {
          this.params[key]='';
          return;
        }
        if(Array.isArray(item)) {
          this.params[key]=[];
          return;
        }
        if(typeof(item)=='object') {
          item.value='';
          return;
        }
        // dump('clear ' + key);
      },
      
      show : function() {
        this.dialogFormVisible = true;
      },
      hide : function() {
        this.dialogFormVisible = false;
      },
      //根据key拿到对应控件当前的显示文字
      getItemDesc(key,value) {
        // if(key=='productId') debugger;
        //不同组件用不同方法处理标签文字,
        //comp-select:从dialog Items中获得相应的option的text
        var item=null;
        for(var v of this.searchItems) {
          if(v.name==key) {
            item=v;
            break;
          }
        }
        if(item.type=='comp-select') {
          var options = item.options;
          var vals = Array.isArray(value) ? value : [value];
          var temp=[];
          for(var i=0;vals[i];i++) {
            var v = vals[i].value || vals[i];
            for(var j=0;options[j];j++) {
              if(v!=options[j].value) continue;
              temp.push(options[j].text);
            }
          }
          return temp.join(',');
        } else if(item.type=='comp-popup-select') {
          //如果实例存在，直接从实例中拿数据
          if(this.$refs[key]) {
            return this.$refs[key][0].text
          }
          return item.displayText || item.text || value;
        }
      },
      getDescAdvParams : function() {
        var text = [];
        //dump(this.searchItems,text);
        this.searchItems.forEach((item,index)=>{
          var textJoin = item.type=='comp-text' ? "包含" : "等于";
          if(this.params[item.name]===undefined) return;
          if(this.params[item.name]=='') return;
          // dump(item.name);
          //取组件的显示文本，可能是displayText属性
          var temp = this.$refs[item.name][0].displayText || this.$refs[item.name][0].value;
          text.push(`${item.title} ${textJoin} ${temp}`);
        });
        return text.join("<br/>");
      },
      handleOk:function() {
        this.dialogFormVisible=false;
        //将已确认的搜索条件形成文字描述

        // return text.join("<br/>");
        this.descAdvParams = this.getDescAdvParams();
        //抛出
        this.$emit('select',this.params);
      },

      //根据配置信息,从服务器获得所有搜索控件，mounted中触发，
      //所有的搜索控件在Config/Searchitems_config.php中定义好了.
      setSearchItems : function() {
        // this.searchConfig = opt;
        var opt = this.items;
        //从服务器获得高级搜索条目
        var url='?controller=searchitems&action=getcomps';
        //将this.searchitems转变成数组
        var temp=[]
        for(var key in opt) {
          var _temp = typeof(opt[key])=="object"&&opt[key].hasOwnProperty('value') ? opt[key] : {value:opt[key]};
          _temp.key = key;
          temp.push(_temp);
        }
        var params={items:temp};
        this.$http.post(url,params).then((res)=>{
          if(!res.data.success) {
            this.$notify.error({
              'title':'表单项获取失败',
              'message':res.data.msg,
            });
            return false;
          }
          //开始处理返回的items
          var items = res.data.items;

          //处理display-text属性，默认的displayTex是从配置项中获得
          this.searchItems = items;
          for(let i=0;this.searchItems[i];i++) {
            let key = this.searchItems[i].name;
            if(!Common.isset(this.searchItems[i],'displayText')) continue;
            this.searchItems[i].displayText=opt[key].text||'';
          }

          //根据服务器返回的字段定义,为this.params进行初始化
          // dump(this.params);return;
          items.forEach((item,i)=>{
            //不能直接进行设置,因为params中的变量和控件存在绑定关系,简单创建变量不能生成绑定关系,必须使用Vue.set来进行设置
            // this.params[item.name]='';
            // if(item.name=='productId') dump('设置 productId ',opt);
            let temp;
            if(!Common.isset(opt,item.name)) temp='';
            else if(typeof(opt[item.name])=='string') temp=opt[item.name]
            else if(Common.isset(opt[item.name],'value')) temp = opt[item.name].value;
            else temp = opt[item.name]
            vue.set(this.params,item.name,temp);
          });

          // dump('高级弹窗从服务器获得表单项ok,请求参数:',this.items,'searchItems:',this.searchItems,',params:',this.params);

          // 根据 this.searchItems 异步载入组件,
          var temp = [];
          var mapArr = {};
          for(var k in this.searchItems) {
            var c = this.searchItems[k];
            var compName = c.type;
            temp.push(`_vue!pathComponent/${compName}`);
            mapArr[compName] = mapArr[compName]||[];
            mapArr[compName].push({index:k});
          }
          var that  = this;
          require(temp,function(){      
            // console.log('import over');    
            for(var a of arguments) {
              for(var aa of mapArr[a.options.name]) {
                // var key = aa.name;
                // var index = aa.ind
                that.searchItems[aa.index].content = a;
              }
            }
            // that.$nextTick(()=>{

            // });
            // dump(that,that.searchItems);
            dump('高级弹窗子组件异步载入完成,searchItems:',that.searchItems);
            // vue.nextTick(function(){
            //   dump(that);
            //   that.$emit('on-mount-items',that);
            // },that);
            //如果在el-table使用自定义组件,会渲染失败,可能是el-table的bug,所以这里要重新渲染下
            // that.$refs.table.doLayout();
          });
          this.$emit('on-mount-items',this);


        }).catch(function (error) {
          console.error(error);
          this.$notify.error({
            'title':'请求失败',
            'message':'请求失败,检查url或者其他设置'
          });
        });
      },

      //设置某个表单项的默认值,colForKey改变时触发
      setItem : function(key,value) {
        // vue.set(this.params,key,value);
        this.paramsInit[key]=value;
        /*
        this.$bus.$on('sendMsg', content => { 
          console.log('fire');
          this.msg = content;
        });
        this.$bus.$emit('sendMsg','fuck liweiwei');
        */

        //if(!Common.isset(this.params,key)) return;  
        
        // var item = this.params[key];
        // if(typeof(item)=='string' || typeof(item)=='number' || typeof(item)=='boolean') {
        //   this.params[key]=value;
        //   return;
        // }
        // if(Array.isArray(item)) {
        //   this.params[key]=value;
        //   return;
        // }
        // if(typeof(item)=='object') {
        //   item.value=value;
        //   return;
        // }
      },
    },
    mounted: function() {
      dump('advdialog mounted, load items from servers,参数:',this.items);
      var bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
      bodyHeight = bodyHeight - 230;
      this.cardBodyHeight['max-height'] = bodyHeight+'px';
      //onmount事件延迟到ajax获得表单项之后再执行.
      // this.$emit('on-mount',this);
      this.setSearchItems();
      // dump(this);
    },
    watch: {
      // items : function(val,oldVal) {
      //   this.setItem(val.col,val.value);
      // }
    },

  });
});

</script>